﻿/*
	Copyright 2008 CATsoft Development GmbH

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
/*
	Uitilities
*/

/***********************************************************************
 XML Http Handling
***********************************************************************/
function comm(){
	
	var request;
	var connected = false;
	var timer = -1;
	var timeout = 10000;
	var timeoutretry = 6 * timeout; // retry time if service not available
	var connectedTimeout = 2 * timeout;	// connected expiring time

	/* Initialize Communication object */
	comm.prototype.init = function()
{
		if(request == null)
			request = new XMLHttpRequest();
			// Check if request is pending
		if ((request.readystate > 0 ) && (request.readystate < 4 ))
		{
			// Wait for 10 seconds, cancel request after this
			Sleep(10000);
			if ((request.readystate > 0 ) && (request.readystate < 4 ))
				request.abort();
		}
	}

	/* Send Request sync */
	comm.prototype.sendXMLHttpRequest = function(url, rest) {
	    if (typeof rest == 'undefined')
	        rest = true;
	    // Change space to %20 because of the Linux Gadget
	    url = url.replace(/ /g, "%20");

			//safetycheck if connection is ok and retry if not
			if(!this.connected || !framework.system.network.online){
				return null;
			}

	    this.init()
	    var parser;
	    try {
	        request.open("GET", url, false);
	        if (rest) {
	            request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	            request.setRequestHeader("Content-Type", "text/xml");
	        }
	        request.send();
	        if ((request.status == 200) || (request.status == 0)) {
							this.connected = true;
	            parser = new SimpleXmlParser(request.responseXml);
	        }
	        else if (request.status == 503) {        // Temp. offline
	            showError("Info", "Server Message: Request status=" + request.status + "/" + request.responseText);
	            parser = null;
	        }
	        else {
	            showError("Info", "Server Message: Request status=" + request.status + "/" + request.responseText);
	            parser = null;
	        }
	    }
	    catch (e) {
	        showError("Error", e.description + " (" + request.status + ")\n" + url);
	    }
	    return parser
	}

	/* Send Request async */
	comm.prototype.sendXMLHttpRequestAsync = function( url, rest )
	{
		if (typeof rest == 'undefined' ) rest = true;

		this.init();
		try {
			request.open("GET", url, true );
			if(rest)
			{
				request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ); 
				request.setRequestHeader( "Content-Type", "text/xml" );
			}
			request.onreadystatechange = this.sendXMLHttpRequestAnswer;
			request.send();
		}
		catch(e)
		{
				showError("Error", e.description+ " (" + request.status + ")\n"+url);
		}
		return
	}

	/* Get Answer */
	comm.prototype.sendXMLHttpRequestAnswer = function()
	{
		switch(request.readyState)
		{
			case 4:
							if (request.status == 200) 
								parser = new SimpleXmlParser(request.responseXml);
							else
								showError("Info", "Comm error " + request.status );
							break;
			default:
							break;
		}
	}		

	/* Test if RTM online and responding within timeout */
	comm.prototype.testConnection = function(callback){
		var url = RTM.createURL("rtm.test.echo", ["auth_token=" + RTM.token]);
		if(!framework.system.network.online){
			this.onTimeout(callback);
			return;
		}
		this.init();

		request.onreadystatechange = function(){COMM.onTestStateChange(callback); };
		this.timer = view.setTimeout( function(){COMM.onTimeout(callback); }, timeout);
		
		try{
			request.open("GET", url, true);
			request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
			request.send();
		} catch(e) {
			showError("Error", e.description + " (" + request.status + ")\n" + url);
		}
	}
	
	comm.prototype.onTimeout = function(callback){
		this.connected = false; 
		RTM.connected = false;
		request.abort();
		view.setTimeout(function() {COMM.testConnection(callback); }, timeoutretry);
	}
	
	comm.prototype.onTestStateChange = function(callback){
		if(request.readyState == 4){
			if(request.status == 200){
				this.connected = true;
				view.clearTimeout(this.timer);
				if(callback != undefined && callback != null)
					callback();
				}
				view.setTimeout(function(){ COMM.connected = false; }, connectedTimeout);	
			}
		}
	
 }

/***********************************************************************
 Open URL
***********************************************************************/
function OpenURL(url){
	var winShell = new ActiveXObject("Shell.Application");
  winShell.ShellExecute( url ); 
	return false;
}

/***********************************************************************
 Convert system datestring to custom datestring
***********************************************************************/
function parseDate( s ){
	var ds = "";
	var i = s.indexOf( " " );
	var day = s.substr( 0, i  );
	s = s.substr( i + 1);
	i = s.indexOf( " " )
	var month = s.substr( 0, i  );
	s = s.substr( i + 1);
	i = s.indexOf( " " )
	if( i == 0 )
	{
		year = s;
		time = "";
	}
	else
	{
		year = s.substr( 0, i );
		s = s.substr( i + 1);

		i = s.indexOf("at" );
		if( i >-1 )
			s = s.substr(0, i ) + s.substr( i + 3 )
		time = "T" + s;
	}

	if(! ( (parseInt( month ) >= "0" ) && (parseInt( month ) <= "11" ))){

		i = FREQ_MONTHNAMES.indexOf( month );
		j = FREQ_MONTHNAMES.lastIndexOf( ";", i );
		month = FREQ_MONTHNAMES.substr( j + 1, i - j - 2 )
	}
	return year + "-" + month + "-" + day + time
}

/***********************************************************************
 Convert custom datestring to system datestring
***********************************************************************/
function formatDate( d, hasTime ){
	var month = d.getMonth();
	var datestring = d.getDate();
	var mins = d.getMinutes();

	var i = FREQ_MONTHNAMES.indexOf( month + ":" );
	i = FREQ_MONTHNAMES.indexOf( ":", i );
	var j = FREQ_MONTHNAMES.indexOf( ";", i );
	datestring = datestring + " " + FREQ_MONTHNAMES.substr( i + 1, j - i - 1 ) + " " + d.getFullYear()
	if(hasTime == 1)
	{
		if(mins<10)
			mins = "0" + mins
		datestring = datestring + " at " + d.getHours() + ":" + mins;
	}
	return datestring
}

/***********************************************************************
Convert custom datestring to system datestring
***********************************************************************/
function parseMonthName(due) {
    var s = FREQ_MONTHNAMESx;
    var i, j, pos, n, m;
    var enMonth = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

    m = 0;
    while(true)
    {
        i = s.indexOf(":",i+1);
        if( i == -1 )
            break;
        j = s.indexOf(";",i);
        n = s.substr( i + 1, j - i - 1).toLowerCase();
        
        pos = due.toLowerCase().indexOf(n);
        if ( pos > -1) {
            due = due.substr(0, pos) + enMonth[m] + due.substr(pos + n.length);
            return due
        }
        m++;
    }

    s = FREQ_MONTHNAMES;
    m = 0;
    while (true) {
        i = s.indexOf(":", i + 1);
        if (i == -1)
            break;
        j = s.indexOf(";", i);
        n = s.substr(i + 1, j - i - 1).toLowerCase();
        
        pos = due.toLowerCase().indexOf(n);
        if (pos > -1) {
            due = due.substr(0, pos) + enMonth[m] + due.substr(pos + n.length);
            return due
        }
        m++;
    }
    
   return due; 
}

/***********************************************************************
Convert characters in XML String
***********************************************************************/
function xmlEscape( s ){
var t = "";

	for(var i=0; i < s.length; i++){
		switch( s.charAt(i) ){	
				case "&": t = t + "&amp;";
											break;
				case '"': t = t + "&quot;";
											break;
				case "<": t = t + "&lt;";
											break;
				case ">": t = t + "&gt;";
											break;
				default: t = t + s.charAt(i);
		}
	}
	return t;
}

/***********************************************************************
 Return hrs:minuts form datestring
***********************************************************************/
function hourminutes(dx, Time24) {
    if (dx == "")
        ret = "";
    else {
        var h = dx.getHours();
        var i = dx.getMinutes();
        var ret;
        if (Time24 == 0) {
            if (h > 12) {
                suffix = 'pm'
                h -= 12;
            }
            else
                suffix = 'am';
        }

        ret = ((h < 0 || h > 9 ? "" : "0") + h + ":" + (i < 0 || i > 9 ? "" : "0") + i);
        if (Time24 == 0)
            ret = ret + suffix;
    }
return ret;
}

/***********************************************************************
 Return yyyy-mm-dd hrs:minuts form datestring
***********************************************************************/
function createDate(s) {

    if (s == "")
        dx = ""
    else {

        var y = s.substr(0, 4);
        var m = s.substr(5, 2) - 1;
        var d = s.substr(8, 2);
        var h = s.substr(11, 2);
        var i = s.substr(14, 2);
        var s = s.substr(17, 2);

        var dx = new Date()
        dx.setUTCFullYear(y, m, d);
        dx.setUTCHours(h, i, s);
    }
    return dx;
}

/***********************************************************************
 Return weekday
***********************************************************************/
function getWeekDay(d){
	var 	i, j, day, daystring = "";
	d = d + ",";

	var p = d.indexOf( ",");
	while( p >= 0) {
		day = d.substr( 0, p );
		i = FREQ_WEEKDAYS.indexOf( day );
		j = FREQ_WEEKDAYS.indexOf( ";", i );
		daystring = daystring + FREQ_WEEKDAYS.substr( i + 3, j - i - 3 ) + ", ";
		d = d.substr( p + 1);
		p = d.indexOf( ",");
	}
	daystring = daystring.substr( 0, daystring.length - 2 );
	return daystring;
}

/***********************************************************************
 List Colors
***********************************************************************/
function getListColor( id ){
	var color = options.getValue( "color" + id );

	if (color=="")
		color = "#FFFFFF"

	return color;
}

/***********************************************************************
 Selected lists
***********************************************************************/
function getListShow( id, position ){
var show = options.getValue( "show" + id );

    if (show.length == 0) 
    {
        if (position == "-1")
            show = "true"
        else
            show = "false";
    }
    else 
    {
        if (show == "1")
            show = "true"
        else
            show = "false";
    }
	return show;
}

/***********************************************************************
  UTF 8 Encoding
***********************************************************************/
function encode_utf8(rohtext) {
	 // dient der Normalisierung des Zeilenumbruchs
    rohtext = rohtext.replace(/\r\n/g, "\n");
	 var utftext = "";
	 for(var n=0; n<rohtext.length; n++)
	{
		var c=rohtext.charCodeAt(n);
		if (c<128)
			utftext += String.fromCharCode(c);
		else if((c>127) && (c<2048)) 
		{
			utftext += String.fromCharCode((c>>6)|192);
			utftext += String.fromCharCode((c&63)|128);
		}
		else if((c>2047) && (c < 65536))
		{
			utftext += String.fromCharCode((c>>12)|224);
			utftext += String.fromCharCode(((c>>6)&63)|128);
			utftext += String.fromCharCode((c&63)|128);
		}
		else 
		{
		 utftext += String.fromCharCode((c>>18)|240);
		 utftext += String.fromCharCode(((c>>12)&63)|128);
		 utftext += String.fromCharCode(((c>>6)&63)|128);
		 utftext += String.fromCharCode((c&63)|128);
		}
	}
	return utftext;
}

/***********************************************************************
  Create unique array
***********************************************************************/
function addToArray( currArray, value, unique ){
	var found = false;
	if( unique )
	{
		for( var i=0; i < currArray.length; i++)
			if(currArray[i] == value)
			{
				found = true;
				break;
			}
	}
	if(!found)
		currArray.push( value );
}

/***********************************************************************
  Sleeps
***********************************************************************/
function Sleep(delay)
{
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

/***********************************************************************
Show Error
***********************************************************************/
function showError( level, message) {

    var item = new ContentItem();
    item.heading = "Error";
    item.snippet = level;
    try {
        plugin.AddContentItem(item, gddItemDisplayAsNotification);
    }
    catch (e) {
        alert(level + "\n" + message);
    }
}


/***********************************************************************
  Show Callstack
***********************************************************************/
function showCallStack(){
	var f=showCallStack,result="Call stack:\n";

	while((f=f.caller)!==null){
		var sFunctionName = f.toString().match(/^function (\w+)\(/)
		sFunctionName = (sFunctionName) ? sFunctionName[1] : 'anonymous function';
		result += sFunctionName;
		result += getArguments(f.toString(), f.arguments);
		result += "\n";
	}
	debug.info(result);
}

function getArguments(sFunction, a) {
	var i = sFunction.indexOf(' ');
	var ii = sFunction.indexOf('(');
	var iii = sFunction.indexOf(')');
	var aArgs = sFunction.substr(ii+1, iii-ii-1).split(',')
	var sArgs = '';
	for(var i=0; i<a.length; i++) {
	var q = ('string' == typeof a[i]) ? '"' : '';
	sArgs+=((i>0) ? ', ' : '')+(typeof a[i])+' '+aArgs[i]+':'+q+a[i]+q+'';
	}
	return '('+sArgs+')';
}